import React, { Component } from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { Modal, Button, Table, Input, Select, Form, message, Tree, Spin, } from "antd";
import { connect } from "dva";
import { doRelatedQuestion } from "@/services/datastatistics";
import { knowledgeClassification } from "@/services/knowledgemanagement";
import { fetchGraphCategory } from "@/services/knowledgegraph";
import menuCheck from "@/utils/menuCheck";
import styles from "./RelatedKnowledge.less";
const { Search } = Input;
const { Option } = Select;

class RelatedKnowledge extends Component {
	constructor(props) {
		super(props);
		this.state = {
			Butloading: false,
			query: {
				page: 1,
				limit: 10,
				field: 1,
				question: "",
				query: "",
				// robotId: this.props.currentUser.robotId,
			},
			rowList: [],
			total: 0,
			dataList: [],
			queryType: [
				{
					name: formatMessage({ id: 'utils.relatedKnowledge.knowledgeOverview' }),
					key: 1,
				},
				{
					name: formatMessage({ id: 'utils.relatedKnowledge.knowledgeMap' }),
					key: 3,
				},
			],
			treeData: [],
			selectedKeys: [],
			defaultExpandedKeys: [],
			categoryParentPath: "",
			treeLoading: false,
		};
	}

	componentDidMount() {
		if (this.props.onRef) {
			this.props.onRef(this);
		}
		// this.getList();
	}

	setRelatedList = (data) => {
		if (data) {
			let arr = [];
			for (let item of data) {
				arr.push({ ...item, id: item.id, basicQuestion: item.basicQuestion });
			};
			console.log(arr);
			this.setState({ rowList: arr });
		}
	};

	setRelatedListFromHot = (data) => {
		if (data) {
			let arr = [];
			for (let item of data) {
				arr.push({ id: item.qaId, basicQuestion: item.question });
			}
			console.log(arr);
			this.setState({ rowList: arr });
		}
	};

	getList = (flag, robotIdFromLearn) => {
		this.setState({ loading: true, robotIdFromLearn }, () => {
			this.getTableData();
		});
	};

	getListForHot = (obj) => {
		const { dispatch, hotLabelId } = this.props;
		let url = "relatedKnowledge/getRelatedListForHot";
		if (hotLabelId) {
			obj.hotLabelId = hotLabelId;
			dispatch({
				type: url,
				payload: obj,
				callback: (res) => {
					this.setState({
						dataList: res.records ? res.records : "",
						total: res.total,
						loading: false,
					});
				},
			});
		}
	};

	showDrawer = () => {
		this.setState({ visible: true });
	};

	onClose = (type) => {
		let { query } = this.state;
		query.field = 1;
		query.query = "";
		query.current = 1;
		this.setState({ visible: false, query, Butloading: false, rowList: [] }, () => {
			this.props.onClose(type);
		});
	};

	handelTablePageChange = (value) => {
		const { query } = this.state;
		query.page = value;
		this.setState({ query, }, () => {
			this.getTableData();
		});
	};

	doSearch = (value) => {
		const { query } = this.state;
		query.query = value;
		query.page = 1;
		this.setState({ query, }, () => {
			this.getTableData();
		});
	};

	doSelect = (row) => {
		const { hotType } = this.props;
		let { rowList } = this.state;
		if (hotType === 1) {
			rowList = [row];
		} else {
			rowList.push(row);
		};
		this.setState({ rowList }, () => {
			if (this.props.getRelatedList) {
				this.props.getRelatedList(rowList);
			}
		});
	};

	handelOk = () => {
		const { rowList } = this.state;
		const { hotType, form } = this.props;
		this.setState({ Butloading: true });
		const that = this;
		//判断是否是热点问题打开的关联问弹窗 若是 则判断是底部标签还是自定义标签
		if (hotType === 0 || hotType === 1) {
			if (hotType === 1) {
				// 底部标签 则判断是否填写了标签名称
				const info = form.getFieldValue("tagName");
				if (!info) {
					message.error(formatMessage({ id: 'utils.relatedKnowledge.enterTagName' }));
					return false;
				};
				that.props.selectAction(rowList, info);
				that.onClose();
			} else {
				//自定义标签 可直接关闭弹窗
				that.onClose();
			}
		} else {
			//判断是否有确定事件的回调 若没有则直接关闭弹窗 若有 则调用回调
			if (this.props.question) {
				return that.doRelationQas(rowList);
			};
			if (that.props.selectAction) {
				that.props.selectAction(rowList);
				that.onClose();
			} else {
				that.onClose();
			}
		}
	};

	/* Function Info
	 * Author:      extrastu
	 * CreateTime:  8/2/2021, 5:20:16 PM
	 * LastEditor:  extrastu
	 * ModifyTime:  8/2/2021, 5:20:16 PM
	 * Description:
	 */
	doRelationQas = async (rowList) => {
		const qaIds = rowList.map((item) => item.id);
		const { question, qaId, type } = this.props;
		const { query } = this.state;
		let obj;
		switch (type) {
			case "WaitProblems":
				obj = {
					qaIds,
					question,
					targetId: qaId,
					qaType: query.field === 1 ? "qa" : query.field === 2 ? "atlasNode" : "dialog",
				};
				break;
			case "answerRecords":
				obj = {
					qaIds,
					question,
					targetId: qaId,
					qaType: query.field === 1 ? "qa" : query.field === 2 ? "atlasNode" : "dialog",
				};
				break;
			default:
				obj = {
					qaIds,
					question,
					targetId: qaId,
				};
				break;
		};
		const res = await doRelatedQuestion(obj);
		// console.log(res);
		if (res) {
			this.setState({ Butloading: false });
		};
		if (res.code === 0) {
			this.onClose("done");
		}
	};

	renderAction = (record) => {
		const { rowList } = this.state;
		const { hotType } = this.props;
		const result = rowList.some((item) => {
			if (item.id === record.id || item.qaId === record.id) {
				return true;
			}
		});
		if (result || (hotType && hotType === 1 && record.isSelect)) {
			return (
				<Button type='primary' onClick={() => this.unSelect(record)}>{formatMessage({ id: 'utils.relatedKnowledge.selected' })}</Button>
			);
		} else {
			return <Button onClick={() => this.doSelect(record)}>{formatMessage({ id: 'utils.relatedKnowledge.select' })}</Button>;

		}
	};

	handelSelectChange = (value) => {
		const { query } = this.state;
		query.field = value;
		query.page = 1;
		this.setState({ query, }, () => {
			this.getTableData();
		});
	};

	/**
	 * 清空标签
	 * @returns {*}
	 */
	resetLabel = () => {
		if (this.props.form) {
			this.props.form.resetFields();
		}
	};

	unSelect = (record) => {
		const { rowList } = this.state;
		const result = rowList.filter((item) => {
			return item.id !== record.id;
		});
		// console.log(result);
		this.setState({ rowList: result, }, () => {
			if (this.props.getRelatedList) {
				this.props.getRelatedList(result);
			}
		});
	};

	/* 获取知识总览树 */
	getKnowledgeTree = async () => {
		const res = await knowledgeClassification({
			urlPrefix: this.props.urlPrefix,
			categoryId: this.props.pathId,
		});
		/* 默认选中所有分类下第一个分类 */
		const selectedKeys =
			res && res[0] && res[0].children && res[0].children[0]
				? [res[0].children[0].id]
				: [];
		const categoryParentPath =
			res && res[0] && res[0].children && res[0].children[0]
				? res[0].children[0].parentPath
				: "";
		this.setState(
			{
				treeData: res ? res : [],
				selectedKeys,
				defaultExpandedKeys: res && res[0] ? [res[0].id] : [],
				categoryParentPath,
				treeLoading: false,
			},
			() => {
				this.getTableData();
			}
		);
	};

	/* 获取知识导图分类 */
	getGraphTree = async () => {
		const res = await fetchGraphCategory({ urlPrefix: this.props.urlPrefix });
		const treeData = [
			{ id: "root", name: "所有分类", parentId: "0", children: res ? res : [] },
		];
		// console.log(treeData);
		const selectedKeys = res && res[0] ? [res[0].id] : [];
		this.setState(
			{
				treeData,
				selectedKeys,
				defaultExpandedKeys: ["root"],
				treeLoading: false,
			},
			() => {
				this.getTableData();
			}
		);
	};

	/* 切换类型 */
	changeField = (key) => {
		let { query } = this.state;
		query.field = key;
		query.page = 1;
		this.setState({ query, }, () => {
			this.treeToData();
		});
	};

	/* 知识总览/知识导图的切换-需要先加载分类-再加载表格数据 */
	treeToData = () => {
		this.setState({ treeLoading: true, }, () => {
			const { query } = this.state;
			switch (query.field) {
				case 1:
					this.getKnowledgeTree();
					break;
				case 3:
					this.getGraphTree();
					break;
			}
		});
	};

	/* 树分类的选择 */
	onSelectTree = (selectedKeys, e) => {
		let { query } = this.state;
		query.page = 1;
		console.log(e, e.node.props.parentPath);
		this.setState(
			{
				selectedKeys,
				categoryParentPath:
					e.node.props && e.node.props.parentPath
						? e.node.props.parentPath
						: "",
				query,
			},
			() => {
				this.getTableData();
			}
		);
	};

	/* 获取表格数据 */
	getTableData = () => {
		const { query, selectedKeys, categoryParentPath } = this.state;
		this.setState({ loading: true, });
		const { dispatch, qaId, robotId, question, urlPrefix, type, importType } = this.props;
		let url = type === 'WaitProblems' || type === 'answerRecords' ? 'relatedKnowledge/getRelatedListForCapacity' : robotId
			? "relatedKnowledge/getRelatedListForHot"
			: "relatedKnowledge/getRelatedList";
		let obj = {
			current: query.page,
			size: query.limit,
			search: query.query,
			type: query.field,
			// qaId: qaId ? qaId : "",
			// question,
			// categoryId: selectedKeys[0] ? selectedKeys[0] : "",
		};
		/* 知识总览 */
		// if (query.field != 3) {
		// 	obj.categoryParentPath = categoryParentPath;
		// };
		if (robotId) {
			obj.robotId = robotId;
			this.getListForHot(obj);
		} else {
			dispatch({
				type: url,
				payload: { ...obj },
				callback: (res) => {
					this.setState({
						dataList: res.records ? res.records : "",
						total: res.total,
						loading: false,
					});
				},
			});
		}
	};

	render() {
		const { visible, relatedKnowledgeData, hotType, robotId } = this.props;
		const {
			Butloading, query, rowList, dataList, total, loading, queryType,
			selectedKeys, defaultExpandedKeys, treeData, treeLoading,
		} = this.state;
		const { getFieldDecorator } = this.props.form;
		const columns = [
			{
				title: formatMessage({ id: 'utils.relatedKnowledge.basicQuestion' }),
				dataIndex: "basicQuestion",
				key: "basicQuestion",
				width: 200,
			},
			{
				title: formatMessage({ id: 'utils.relatedKnowledge.category' }),
				dataIndex: "categoryNamePath",
				key: "categoryNamePath",
				width: 200,
			},
			{
				title: formatMessage({ id: 'utils.relatedKnowledge.action' }),
				dataIndex: "action",
				key: "action",
				width: 100,
				render: (text, record) => {
					if ((robotId && !hotType) || (robotId && hotType != 1)) {
						return record.isSelect ? (
							<Button type='primary' onClick={() => this.unSelect(record)}>{formatMessage({ id: 'utils.relatedKnowledge.selected' })}</Button>
						) : (
							<Button onClick={() => this.doSelect(record)}>{formatMessage({ id: 'utils.relatedKnowledge.select' })}</Button>
						);
					} else {
						return this.renderAction(record);
					}
				},
			},
		];
		const renderTreeNode = (data) => {
			return data.map((item) => {
				if (item.children && item.parentId == "0") {
					return (
						<Tree.TreeNode title={item.name} key={item.id} parentId={item.parentId} parentPath={item.parentPath}>
							{renderTreeNode(item.children)}
						</Tree.TreeNode>
					);
				} else {
					return (
						<Tree.TreeNode title={item.name} key={item.id} parentId={item.parentId} parentPath={item.parentPath} />
					);
				}
			});
		};

		return (
			<Modal
				title={formatMessage({ id: 'utils.relatedKnowledge.selectRelatedQuestion' })}
				placement='right'
				closable
				onCancel={this.onClose}
				visible={visible}
				width={800}
				footer={[
					<Button onClick={this.onClose}>{formatMessage({ id: 'common.cancel' })}</Button>,
					<Button type='primary' onClick={this.handelOk} loading={Butloading}>{formatMessage({ id: 'common.confirm' })}</Button>,
				]}
				className={styles.relatedKnowledge}
				destroyOnClose
			>
				<Spin spinning={loading}>
					<Select
						defaultValue={query.field}
						style={{ width: "150px", margin: "10px 0" }}
						onChange={this.handelSelectChange}
					>
						<Option value={1}>{formatMessage({ id: 'utils.relatedKnowledge.qaKnowledge' })}</Option>
						<Option value={2}>{formatMessage({ id: 'utils.relatedKnowledge.mapKnowledge' })}</Option>
						<Option value={3}>{formatMessage({ id: 'utils.relatedKnowledge.multipleDialog' })}</Option>
					</Select>

					<Search
						placeholder={formatMessage({ id: 'utils.relatedKnowledge.inputPlaceholder' })}
						onSearch={this.doSearch}
						style={{ width: "300px", margin: "10px" }}
					/>

					<Table
						dataSource={dataList}
						columns={columns}
						bordered
						rowKey={"id"}
						pagination={{
							pageSize: query.limit,
							onChange: this.handelTablePageChange,
							current: query.page,
							total: total,
						}}
						scroll={{ y: 400 }}
					/>
				</Spin>
			</Modal>
		);
	}
}

export default connect(({ user, relatedKnowledge }) => ({
	currentUser: user.currentUser,
	relatedKnowledgeData: relatedKnowledge.data,
}))(Form.create()(RelatedKnowledge));
